'use strict';

const { Service } = require('ee-core');
const Storage = require("ee-core/storage");
const _ = require("lodash");

const { dialog, ipcMain, session } = require('electron');
const fs = require('fs')
const path = require('path')
const XLSX = require('xlsx')

const axios = require('axios');
const httpsProxyAgent = require('https-proxy-agent');
const ExcelJS = require('exceljs');

const { app, BrowserWindow } = require('electron');
const windows = BrowserWindow.getAllWindows();

const FormData = require('form-data');
const qs = require('qs');


// let mainWindow = BrowserWindow.getFocusedWindow();

// // 主进程代码中监听窗口焦点变化
// app.on('browser-window-focus', (event, window) => {
//   mainWindow = window;
// });
let messages = []
let timer = null;



let agrent = ''

/**
 * 示例服务（service层为单例）
 * @class
 */
class ExampleService extends Service {

  constructor(ctx) {
    super(ctx);

    // lowdb数据库
    this.systemDB = Storage.connection("system");
    this.demoDBKey = {
      test_data: "test_data",
    };

    // sqlite数据库
    this.sqliteFile = "sqlitePdd.db";
    let sqliteOptions = {
      driver: "sqlite",
      default: {
        timeout: 6000,
        // verbose: console.log, // 打印sql语法
      },
    };
    this.demoSqliteDB = Storage.connection(this.sqliteFile, sqliteOptions);
  }

  /**
   * test
   */
  async test(args) {
    let obj = {
      status: 'ok',
      params: args
    }

    return obj;
  }

  /*
  * 检查并创建表  goods 表
  */
  async checkAndCreateTableGoods(tableName = "") {
    if (_.isEmpty(tableName)) {
      throw new Error(`table name is required`);
    }
    // 检查表是否存在
    const userTable = this.demoSqliteDB.db.prepare("SELECT * FROM sqlite_master WHERE type=? AND name = ?");
    const result = userTable.get("table", tableName);
    if (result) {
      // console.log('1111');
      return;
    }

    // 创建表
    const create_table_goods = `CREATE TABLE ${tableName}
       (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          userId INTEGER,
          accountId INTEGER,
          total INTEGER,
          type INTEGER,
          datas TEXT
       );`;
    this.demoSqliteDB.db.exec(create_table_goods);
  }

  async getorderlist2(args) {
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      // console.log(agrent);
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          'Cookie': args.cookie
        }
      });

      try {
        let url = ''
        if (args.type == 1) {
          url = `https://mybid.ruten.com.tw/master/my.php?l_type=sel_wait_confirm&p=${args.lutianorderlistcurrentpage}`
        } else {
          url = `https://mybid.ruten.com.tw/master/my.php?l_type=sel_full&p=${args.lutianorderlistcurrentpage}`
        }
        // console.log(url);
        const response = await axiosInstance.get(url)
        console.log('success');
        // console.log(response);
        return JSON.stringify(response.data)
      } catch (error) {
        console.log('error');
        console.error(error);
        return error.code
      }
    }
  }


  async getexportdata(args) {
    try {
      // 创建工作簿对象
      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet 1');

      let allFields = [];

      // 遍历数组对象，获取所有字段名
      args.forEach(obj => {
        const fields = Object.keys(obj);
        allFields = allFields.concat(fields);
      });

      // 使用 Set 对数组进行去重
      const uniqueFields = [...new Set(allFields)];

      // 设置表头
      const headers = uniqueFields
      headers.forEach((header, index) => {
        worksheet.getCell(1, index + 1).value = header;
        worksheet.getColumn(index + 1).width = 15;
      });

      // 辅助函数：下载图片并插入到工作表中
      async function downloadAndInsertImage(worksheet, url, row, col) {
        try {
          const response = await axios.get(url, { responseType: 'arraybuffer' });
          const imageBuffer = response.data;
          const imageId = workbook.addImage({
            buffer: imageBuffer,
            extension: 'png',
          });

          worksheet.addImage(imageId, {
            tl: { col: col - 1, row: row - 1 },
            ext: { width: 100, height: 100 },
          });
        } catch (error) {
          console.error(`下载或插入图片时出错 (row: ${row}, col: ${col}):`, error);
        }
      }

      // 下载图片并插入到工作表中
      for (let rowIndex = 0; rowIndex < args.length; rowIndex++) {
        const rowData = args[rowIndex];
        let hasImage = false;
        for (let colIndex = 0; colIndex < headers.length; colIndex++) {
          const header = headers[colIndex];
          const cell = worksheet.getCell(rowIndex + 2, colIndex + 1);

          if (header === '商品主图' && rowData[header]) {
            const imageUrl = rowData[header];
            await downloadAndInsertImage(worksheet, imageUrl, rowIndex + 2, colIndex + 1);
            hasImage = true;
          } else {
            cell.value = rowData[header];
          }
        }
        if (hasImage) {
          worksheet.getRow(rowIndex + 2).height = 79;
        } else {
          worksheet.getRow(rowIndex + 2).height = 40;
        }
      }

      // 保存 Excel 文件
      // const filePath = '订单.xlsx';  // 替换成你想要保存的文件路径
      // await workbook.xlsx.writeFile(filePath);
      // return '保存成功';
      const result = await dialog.showSaveDialog({
        defaultPath: '订单.xlsx', // 默认文件名
        buttonLabel: '保存', // 保存按钮的文本
        filters: [
          { name: 'Excel文件', extensions: ['xlsx'] }
        ]
      });

      // 如果用户点击了保存按钮
      if (!result.canceled) {
        const filePath = result.filePath;
        // 将工作簿对象写入文件
        // XLSX.writeFile(workbook, filePath);
        await workbook.xlsx.writeFile(filePath);
        return '保存成功'; // 返回文件路径给Vue组件
      } else {
        return null; // 用户取消保存操作
      }

    } catch (error) {
      console.error('生成Excel文件时出错:', error);
      throw new Error('生成Excel文件时出错');
    }
  }

  // 获取订单列表
  async getorderlist(args) {
    let table = "goods";
    await this.checkAndCreateTableGoods(table);
    // console.log(args);

    const selectUser = this.demoSqliteDB.db.prepare(`SELECT * FROM ${table} WHERE userId = ${args.userId} AND accountId = ${args.accountId} AND type = ${args.type}`);
    let selectgoods = selectUser.all()

    let a = {}

    // const selectUser2 = this.demoSqliteDB.db.prepare(`DELETE FROM ${table}`);
    // let selectgoods2 = selectUser2.run()
    // console.log(selectgoods);

    if (selectgoods.length != 0) {
      // 更新
      if (args.stutas == 2) {
        let datas = JSON.parse(selectgoods[0].datas)
        // console.log(datas.length);
        if (datas.length > 0) {
          // console.log(datas[0].ordernumber);
          let b = await this.getorderlist2(args)
          a = {
            code: 3,
            data: b,
            oneordernumber: datas[0].ordernumber
          }
          return a
        } else {
          let b = await this.getorderlist2(args)
          a = {
            code: 2,
            data: b
          }
          return a
        }

      } else {
        // 分页
        let datas = JSON.parse(selectgoods[0].datas)
        // console.log(datas);
        // console.log(datas.length, selectgoods[0].total, args.lutianorderlistcurrentpage * 30);
        // const updateUser = this.demoSqliteDB.db.prepare(`UPDATE ${table} SET total = ?,datas = ? WHERE userId = ${args.userId} AND accountId = ${args.accountId} AND type = ${args.type}`);
        // let c = updateUser.run(args.total, JSON.stringify([]));
        // console.log(c);

        if (datas.length == selectgoods[0].total) {
          let page1Data = datas.slice((args.lutianorderlistcurrentpage - 1) * 30, args.lutianorderlistcurrentpage * 30);
          a = {
            code: 1,
            total: selectgoods[0].total,
            data: page1Data
          }
          return a
        } else {
          if (args.lutianorderlistcurrentpage * 30 <= datas.length) {
            let page1Data = datas.slice((args.lutianorderlistcurrentpage - 1) * 30, args.lutianorderlistcurrentpage * 30);
            a = {
              code: 1,
              total: selectgoods[0].total,
              data: page1Data
            }
            return a
          } else {
            let b = await this.getorderlist2(args)
            a = {
              code: 2,
              data: b
            }
            return a
          }
        }

      }

    } else {
      let b = await this.getorderlist2(args)
      a = {
        code: 2,
        data: b
      }
      return a
    }
  }

  // 获取订单详情
  async getorderdetail(args) {
    // console.log(args);
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          'Cookie': args.cookie
        }
      });
      // console.log(axiosInstance);
      // console.log(`https://mybid.ruten.com.tw/master/view_transaction.php?tno=${args.gno}`);
      try {
        const response = await axiosInstance.get(`https://mybid.ruten.com.tw/master/view_transaction.php?tno=${args.gno}`)
        console.log('success');
        // console.log(response);
        return JSON.stringify(response.data)
      } catch (error) {
        console.log('error');
        console.error(error.code);
        return JSON.stringify(error)
      }
    }

  }

  // 保存数据缓存
  async savesqlitDBdata(args) {
    let data = JSON.parse(args.data)
    let table = "goods";
    await this.checkAndCreateTableGoods(table);
    let a = {}
    const selectUser = this.demoSqliteDB.db.prepare(`SELECT * FROM ${table} WHERE userId = ${data.userId} AND accountId = ${data.accountId} AND type = ${data.type}`);
    let selectgoods = selectUser.all()
    // console.log(`SELECT * FROM ${table} WHERE userId = ${data.userId} AND accountId = ${data.accountId} AND type = ${data.type}`);
    // console.log(selectgoods.length);
    if (selectgoods.length == 0) {
      const insert = this.demoSqliteDB.db.prepare(`INSERT INTO ${table} (userId, accountId, total, type, datas) VALUES (?, ?, ?, ?, ?)`);
      const c = insert.run(data.userId, data.accountId, data.total, data.type, JSON.stringify(data.data));

      let page1Data = data.data.slice((data.page - 1) * 30, data.page * 30);
      a = {
        code: 1,
        data: page1Data
      }
      return a
    } else {
      let datas = JSON.parse(selectgoods[0].datas)
      // console.log(data.nums2);
      if (data.nums2 == 3) {

        let copydats = [...datas, ...data.data];

        const updateUser = this.demoSqliteDB.db.prepare(`UPDATE ${table} SET total = ?,datas = ? WHERE userId = ${data.userId} AND accountId = ${data.accountId} AND type = ${data.type}`);
        let c = updateUser.run(data.total, JSON.stringify(copydats));

        let page1Data = copydats.slice((data.page - 1) * 30, data.page * 30);
        a = {
          code: 1,
          data: page1Data
        }
        return a
      } else if (data.nums2 == 1) {
        let copydats = [...data.data, ...datas];

        const updateUser = this.demoSqliteDB.db.prepare(`UPDATE ${table} SET total = ?,datas = ? WHERE userId = ${data.userId} AND accountId = ${data.accountId} AND type = ${data.type}`);
        let c = updateUser.run(data.total, JSON.stringify(copydats));

        let page1Data = copydats.slice((data.page - 1) * 30, data.page * 30);
        a = {
          code: 1,
          data: page1Data
        }
        return a
      } else if (data.nums2 == 0) {
        const updateUser = this.demoSqliteDB.db.prepare(`UPDATE ${table} SET total = ?,datas = ? WHERE userId = ${data.userId} AND accountId = ${data.accountId} AND type = ${data.type}`);
        let c = updateUser.run(data.total, JSON.stringify(data.data));

        let page1Data = data.data.slice((data.page - 1) * 30, data.page * 30);
        a = {
          code: 1,
          data: page1Data
        }
        return a
      }

    }

  }

  // 保存数据缓存
  async getwipecache(args) {
    let data = args
    let table = "goods";
    await this.checkAndCreateTableGoods(table);
    // console.log(args);
    const selectUser = this.demoSqliteDB.db.prepare(`SELECT * FROM ${table} WHERE userId = ${args.userId} AND accountId = ${args.accountId} AND type = ${args.type}`);
    let selectgoods = selectUser.all()

    if (selectgoods.length > 0) {
      // console.log(selectgoods[0].datas);
      const updateUser = this.demoSqliteDB.db.prepare(`UPDATE ${table} SET datas = ? WHERE userId = ${data.userId} AND accountId = ${data.accountId} AND type = ${data.type}`);
      let c = updateUser.run(JSON.stringify([]));
    }

    let code = {
      code: 200,
      message: '清空所选账号缓存成功'
    }

    return code

    // console.log(selectgoods);

  }


  async changedborder(args) {
    let data = JSON.parse(args.data)
    let table = "goods";
    await this.checkAndCreateTableGoods(table);

    const selectUser = this.demoSqliteDB.db.prepare(`SELECT * FROM ${table} WHERE userId = ${args.userId} AND accountId = ${args.accountId} AND type = ${args.type}`);
    let selectgoods = selectUser.all()
    //console.log(JSON.parse(selectgoods[0].datas).length);

    if (selectgoods.length > 0) {
      let datas = JSON.parse(selectgoods[0].datas)
      datas[args.index - 1] = data
      const updateUser = this.demoSqliteDB.db.prepare(`UPDATE ${table} SET datas = ? WHERE userId = ${args.userId} AND accountId = ${args.accountId} AND type = ${args.type}`);
      let a = updateUser.run(JSON.stringify(datas));

      return a
    }


  }

  async getwatchmessage(args) {
    // console.log(agrent);
    const axiosInstance = axios.create({
      // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
      // 7890
      httpsAgent: new httpsProxyAgent(`${agrent}`),
      headers: {
        Cookie: args.cookie,
        'Content-Type': 'text/event-stream',
        'Origin': 'https://mybid.ruten.com.tw',
        'Referer': 'https://mybid.ruten.com.tw/message/messenger.php',
        'Alt-Svc': 'h3=":443"; ma=86400',
        'Access-Control-Max-Age': '86400',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
      }
    });

    let currentTimestamp = Math.floor(Date.now() / 1000);
    let oneDayInSeconds = 24 * 60 * 60; // 一天的秒数
    let timestamp32 = currentTimestamp + oneDayInSeconds;
    try {
      let url = `https://im.ruten.com.tw/api/im/v2/comet/outer/user/${args.bid_rid}/msg?last_event_id=${currentTimestamp}:0`
      // console.log(axiosInstance.defaults.httpsAgent.proxy);
      // console.log(url);
      const response = await axiosInstance.get(url, {
        responseType: 'stream',  // 设置响应类型为流
        // timeout: 15000
      })
      // console.log(response.data);
      // this.sendMessageToClient(response.data)

      response.data.on('data', chunk => {
        const data = chunk.toString('utf8');
        // console.log(data);  // Print received data
        this.sendMessageToClient(data)
      });
      response.data.on('error', err => {
        console.error(err);  // Handle errors
        this.getwatchmessage(args);
      });

      response.data.on('end', () => {
        // console.log('end');
        this.getwatchmessage(args);
      });

    } catch (error) {
      console.log(error.code);
      this.getwatchmessage(args);
    }
  }

  // 
  async serverWatchmessage(args) {
    //console.log(args);
    this.getwatchmessage(args);
    // this.sendMessageToClient('messagestr')
  }

  async sendMessageToClient(message) {
    const mainWindow = BrowserWindow.getFocusedWindow(); // 或者根据你的窗口创建方式获取窗口对象
    // mainWindow.webContents.send('message-to-front-end', messagestr);
    // console.log(message);
    let messageStrings = message.trim().split('\n').map(str => str.trim());
    let messagesarr = messageStrings.map(str => JSON.parse(str));
    let uniqueArray = Array.from(messagesarr.reduce((map, obj) => map.set(obj.timestamp, obj), new Map()).values());
    uniqueArray.forEach(item => {
      let foundIndex2 = messages.findIndex(
        (item3) => item3.timestamp === item.timestamp
      );
      if (foundIndex2 == -1) {
        messages.push(item)
      }
    });
    // let jsonmess = JSON.parse(message)
    // let foundIndex2 = messages.findIndex(
    //   (item3) => item3.timestamp === jsonmess.timestamp
    // );
    // if (foundIndex2 == -1) {
    //   messages.push(jsonmess)
    // }
    // console.log(messages);

    if (mainWindow && !mainWindow.isDestroyed()) {
      // 检查窗口是否已经被销毁，避免使用已销毁的窗口对象

      if (mainWindow.isVisible()) {
        mainWindow.webContents.send('message-from-main', messages);
        messages = []
      } else {
        //console.log('Window is not visible. Message not sent.');
        // 监听窗口恢复可见状态的事件
        mainWindow.once('restore', () => {
          mainWindow.webContents.send('message-from-main', messages);
          messages = []
        });
      }
    } else {
      // messages.push(JSON.parse(message))

      timer = setInterval(() => {
        const mainWindow2 = BrowserWindow.getFocusedWindow();
        if (mainWindow2 != null) {
          if (messages.length > 0) {
            clearInterval(timer);
            mainWindow2.webContents.send('message-from-main', messages);
            messages = []
          } else {
            clearInterval(timer);
          }

        }
      }, 1000);
    }

  }

  async getmessagecontacts(args) {
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      //console.log(agrent);
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          'Cookie': args.cookie,
          'Content-Type': 'application/json',
          'Origin': 'https://mybid.ruten.com.tw',
          'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
        }
      });
      try {
        const response = await axiosInstance.get(`https://rtapi.ruten.com.tw/api/im/v2/index.php/outer/user/${args.userid}/contacts?offset=1&limit=100`)
        return JSON.stringify(response.data)
      } catch (error) {
        console.log(error.code);
        return ''
      }
    }
  }

  // 第一次获取用户消息列表
  async getAccountmessageService(args) {
    // console.log(args);
    try {
      let ids = args.ids;
      let currentTimestamp = Math.floor(Date.now() / 1000);
      let oneDayInSeconds = 24 * 60 * 60; // 一天的秒数
      let timestamp32 = currentTimestamp + oneDayInSeconds;
      let timestamp64 = Date.now();
      let address = global.agentData.address;
      let port = global.agentData.port;

      if (address !== undefined) {
        let agent = `http://${address}:${port}`;
        //console.log(agent);

        const axiosInstance = axios.create({
          timeout: 10000,
          httpsAgent: new httpsProxyAgent(agent),
          headers: {
            'Cookie': args.cookie,
            'Content-Type': 'application/json',
            'Origin': 'https://mybid.ruten.com.tw',
            'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
          }
        });

        const urls = ids.map(id => `https://rtapi.ruten.com.tw/api/im/v2/index.php/outer/user/${args.bid_rid}/log/msg?to=${id}&q=${timestamp32}&t=${timestamp64}`);
        // console.log(urls);
        const requests = urls.map(url => axiosInstance.get(url));
        return axios.all(requests)
          .then(axios.spread((...responses) => {
            // 所有请求完成后执行此处的代码
            // const validResponses = responses.filter(response => response !== null); // 过滤掉失败的请求
            // const responseData = responses.map(response => response.data);
            const responseData = responses.map((response, index) => {
              let a = {
                id: ids[index],
              }
              if (response.error) {
                console.error(response.error); // 输出错误信息，如果需要的话
                a.data = null
                return a; // 返回一个占位符或者 null，表示该请求失败
              }
              a.data = response.data
              return a; // 返回有效的响应数据
            });
            return responseData;
          }))
          .catch(error => {
            // 处理请求过程中的错误
            console.error(error.code);
            // throw error; // 继续向上抛出错误，以便外部调用捕获
            return undefined
          });
      } else {
        throw new Error('Address is undefined');
      }
    } catch (error) {
      console.error('Error in getAccountmessageService:', error);
      // throw error; // 继续向上抛出错误，以便外部调用捕获
    }
  }

  // 发送消息
  async sendmessageService(args) {
    // console.log(args)

    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      let axiosInstance
      // multipart/form-data
      // application/x-www-form-urlencoded
      let url = ''
      const formData = new FormData();
      let a = {}
      let params
      if (args.type != 'base64') {
        axiosInstance = axios.create({
          // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
          // 7890
          httpsAgent: new httpsProxyAgent(agrent),
          headers: {
            'Cookie': args.cookie,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'https://mybid.ruten.com.tw',
            'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
          }
        });
        url = `https://im.ruten.com.tw/api/im/v2/index.php/outer/user/${args.userid}/msg?to=${args.to}`
        let toarr = [args.to]
        a.to = toarr
        a.userid = args.userid
        a.type = args.type
        a.msg = args.msg
        if (args.type == "sticker") {
          a.sid = args.sid
        }
        params = JSON.stringify(a)
      } else {
        let currentDate = new Date();

        // 获取当前时间的毫秒级时间戳
        let timestamp64 = currentDate.getTime();

        url = `https://im.ruten.com.tw/api/im/v2/index.php/outer/user/${args.userid}/img/${timestamp64}/msg?to=${args.to}`
        axiosInstance = axios.create({
          // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
          // 7890
          httpsAgent: new httpsProxyAgent(agrent),
          headers: {
            'Cookie': args.cookie,
            'Content-Type': 'multipart/form-data',
            'Origin': 'https://mybid.ruten.com.tw',
            'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
          }
        });
        const base64Image = args.msg;
        let filename = 'temp-image.png'

        // 从Base64数据中提取图片的Content-Type和数据部分
        const matches = base64Image.match(/^data:([A-Za-z-+/]+);base64,(.+)$/);
        const contentType = matches[1]; // 图片的Content-Type
        const base64Data = matches[2]; // 图片的Base64数据

        let slashIndex = contentType.indexOf('/');
        let imgtype = slashIndex !== -1 ? contentType.slice(slashIndex + 1) : ''

        if (imgtype != '') {
          filename = `temp-image.${imgtype}`
        }
        // 将Base64数据解码为Buffer
        const bufferData = Buffer.from(base64Data, 'base64');

        // 创建临时文件路径
        const tempFilePath = path.join(__dirname, filename);

        // 将Buffer写入临时文件
        fs.writeFileSync(tempFilePath, bufferData);

        // 创建文件流
        const fileStream = fs.createReadStream(tempFilePath);
        formData.append('file', fileStream)
        params = formData
      }

      try {
        const response = await axiosInstance.post(url, params)
        return JSON.stringify(response.status)
      } catch (error) {
        // console.log(axiosInstance.defaults.httpsAgent.proxy);
        console.log(error);
        return ''
      }
    }
  }

  // 获取商品信息
  async getgoodsitemsService(args) {
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          'Content-Type': 'application/json',
          'Origin': 'https://mybid.ruten.com.tw',
          'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
        }
      });
      try {
        const response = await axiosInstance.get(`https://rapi.ruten.com.tw/api/items/v2/list?gno=${args.ids}`)
        return JSON.stringify(response.data)
      } catch (error) {
        console.log(error.code);
        return ''
      }
    }
  }

  // 获取订单信息
  async getorderitemsService(args) {
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          Cookie: args.cookie,
          'Content-Type': 'application/json',
          'Origin': 'https://mybid.ruten.com.tw',
          'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
        }
      });
      try {
        const response = await axiosInstance.get(`https://alert.ruten.com.tw/rutenim/transinfo.php?type=${JSON.stringify(args.type)}&no=${JSON.stringify(args.no)}`)
        return JSON.stringify(response.data)
      } catch (error) {
        console.log(error.code);
        return ''
      }
    }
  }

  // 获取历史消息
  async getoldmessageService(args) {
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      let timestamp64 = Date.now();
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          Cookie: args.cookie,
          'Content-Type': 'application/json',
          'Origin': 'https://mybid.ruten.com.tw',
          'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
        }
      });
      try {
        const response = await axiosInstance.get(`https://rtapi.ruten.com.tw/api/im/v2/index.php/outer/user/${args.bid_rid}/log/msg?to=${args.id}&q=${args.timestamp}&t=${timestamp64}`)
        return JSON.stringify(response.data)
      } catch (error) {
        console.log(error.code);
        return ''
      }
    }
  }

  // 选择图片
  async selectimgService(args) {
    try {
      const result = await dialog.showOpenDialog({
        properties: ['openFile'],
        filters: [
          { name: 'DB Files', extensions: ['jpg', 'png'] },
          // 可以添加其他文件类型的过滤器
        ],
      });

      if (!result.canceled && result.filePaths.length > 0) {
        const filePath = result.filePaths[0];
        try {
          // 读取文件内容
          const fileContent = fs.readFileSync(filePath);
          // 获取文件扩展名
          const extension = path.extname(filePath).toLowerCase();
          // 根据文件扩展名确定 MIME 类型
          let mimeType = '';
          if (extension === '.jpg' || extension === '.jpeg') {
            mimeType = 'image/jpeg';
          } else if (extension === '.png') {
            mimeType = 'image/png';
          } else if (extension === '.gif') {
            mimeType = 'image/gif';
          } else {
            throw new Error('Unsupported file type');
          }

          // 将文件内容转换为 Base64
          // image/
          const base64Data = Buffer.from(fileContent).toString('base64');
          // 生成 Data URL
          const dataUrl = `data:${mimeType};base64,${base64Data}`;

          return dataUrl
        } catch (error) {
          console.error('读取文件出错:', error);
          return ''
        }
      }
    } catch (err) {
      console.log(err);
      return ''
    }
  }

  // 获取单独消息用户
  async getalonemessageuserService(args) {
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          Cookie: args.cookie,
          'Content-Type': 'application/json',
          'Origin': 'https://mybid.ruten.com.tw',
          'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
        }
      });
      try {
        const response = await axiosInstance.get(`https://rtapi.ruten.com.tw/api/im/v2/index.php/outer/user/${args.bid_rid}/favorlist/user?id=${args.id}`)
        return JSON.stringify(response.data)
      } catch (error) {
        console.log(error.code);
        return ''
      }
    }
  }

  // 批量获取未读消息数量
  async getmessageunreadService(args) {
    // console.log(args);
    let jsonargs = JSON.parse(args)
    try {
      let address = global.agentData.address;
      let port = global.agentData.port;

      if (address !== undefined) {
        let agent = `http://${address}:${port}`;
        // console.log(agent);
        const urls = jsonargs.map(item => `https://rtapi.ruten.com.tw/api/im/v2/index.php/outer/user/${item.bid_rid}/unread`);
        // console.log(urls);
        // const requests = urls.map(url => axiosInstance.get(url));
        const requests = urls.map((url, index) => {
          const axiosInstance = axios.create({
            timeout: 10000,
            httpsAgent: new httpsProxyAgent(agent),
            headers: {
              'Cookie': jsonargs[index].cookie,
              'Content-Type': 'application/json',
              'Origin': 'https://mybid.ruten.com.tw',
              'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
            }
          });
          // return axiosInstance.get(url);
          return axiosInstance.get(url)
            .then(response => {
              return {
                id: jsonargs[index].label,
                data: response.data
              };
            })
            .catch(error => {
              if (error.code == 'ECONNREFUSED') {
                return {
                  id: jsonargs[index].label,
                  data: error.code // 或者返回一个占位符对象，表示请求失败
                };
              } else {
                return {
                  id: jsonargs[index].label,
                  data: null // 或者返回一个占位符对象，表示请求失败
                };
              }
              
            });
        });

        return Promise.all(requests);
        // return axios.all(requests)
        //   .then(axios.spread((...responses) => {
        //     // 所有请求完成后执行此处的代码
        //     console.log(responseData);
        //     const responseData = responses.map((response, index) => {
        //       let a = {
        //         id: jsonargs[index].bid_rid,
        //       }
        //       if (response.error) {
        //         console.error(response.error); // 输出错误信息，如果需要的话
        //         a.data = null
        //         return a; // 返回一个占位符或者 null，表示该请求失败
        //       }
        //       a.data = response.data
        //       return a; // 返回有效的响应数据
        //     });
        //     return responseData;
        //   }))
        //   .catch(error => {
        //     // 处理请求过程中的错误
        //     console.error(error.code);
        //     // throw error; // 继续向上抛出错误，以便外部调用捕获
        //     // return undefined
        //   });
      } else {
        console.log('Address is undefined');
        throw new Error('Address is undefined');
      }
    } catch (error) {
      console.error('Error in getAccountmessageService:', error);
      // throw error; // 继续向上抛出错误，以便外部调用捕获
    }
  }

  // 验证cookie
  async verificationcookieService(args) {
    let address = global.agentData.address
    let port = global.agentData.port
    if (address != undefined) {
      agrent = `http://${address}:${port}`
      const axiosInstance = axios.create({
        // 如果目标 URL 是 HTTPS，需要提供一个自定义的 HTTPS 代理代理器
        // 7890
        httpsAgent: new httpsProxyAgent(`${agrent}`),
        headers: {
          Cookie: args.cookie,
          'Content-Type': 'application/json',
          'Origin': 'https://mybid.ruten.com.tw',
          'Referer': 'https://mybid.ruten.com.tw/message/messenger.php'
        }
      });
      try {
        const response = await axiosInstance.get(`https://rtapi.ruten.com.tw/api/im/v2/index.php/outer/user/${args.userid}/unread`)
        return JSON.stringify(response.data)
      } catch (error) {
        console.log(error.code);
        return ''
      }
    }
  }



}

ExampleService.toString = () => '[class ExampleService]';
module.exports = ExampleService;